package cn.edu.nuc.bre.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.nuc.bre.dto.UserInfo;
import cn.edu.nuc.bre.service.interfaces.GroupService;
import cn.edu.nuc.bre.service.interfaces.UserService;

/**
 * 用户服务
 * 
 * @author Mine
 * @since 2016年11月10日_上午11:06:23
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private IdentityService is;
	@Autowired
	private GroupService gs;

	@Override
	public boolean add(User one) {
		if (one != null) {
			if (is.createUserQuery().userId(one.getId()).singleResult() == null) {
				is.newUser(one.getId());// 要显式写一下
				is.saveUser(one);
				return true;
			} else {
				System.out.println("用户已存在...");
			}
		} else {
			System.out.println("参数为空...");
		}
		return false;
	}

	@Override
	public boolean edit(User one) {
		if (one != null) {
			User temp = is.createUserQuery().userId(one.getId()).singleResult();
			if (temp != null) {
				temp.setFirstName(one.getFirstName());
				temp.setLastName(one.getLastName());
				temp.setPassword(one.getPassword());
				temp.setEmail(one.getEmail());
				is.saveUser(temp);// 直接修改
				return true;
			} else {
				System.out.println("用户不存在...");
			}
		} else {
			System.out.println("参数为空...");
		}
		return false;
	}
	@Override
	public boolean editPWD(String uid, String oldPW, String newPW) {
		if(is.checkPassword(uid, oldPW)){
			User temp = is.createUserQuery().userId(uid).singleResult();
			temp.setPassword(newPW);
			is.saveUser(temp);
			return true;
		}
		return false;
	}
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public boolean delete(String uid) {
		boolean flag = false;
		try {
			// 删除旧关系
			List<Group> groups = this.findGroupsById(uid);
			if (groups != null) {
				for (Group group : groups) {
					is.deleteMembership(uid, group.getId());
				}
			}
			is.deleteUser(uid);
			flag = true;
		} catch (Exception e) {
			throw new RuntimeException("异常了...");
		}
		return flag;
	}

	@Override
	public User findById(String uid) {
		return is.createUserQuery().userId(uid).singleResult();
	}

	@Override
	public UserInfo Login(String uid, String pw) {
		UserInfo info = null;
		if (is.checkPassword(uid, pw) == true) {
			info = this.findUserInfoById(uid);
		}
		return info;
	}

	@Override
	public UserInfo findUserInfoById(String uid) {
		UserInfo info = new UserInfo();
		info.setUser(this.findById(uid));
		info.setGroups(this.findGroupsById(uid));// 获取所属角色列表
		return info;

	}

	// 间接调用baseEditGroupShip
	@Override
	public boolean editGroupShip(String uid, String oneGid, boolean isNoticeOfficer) {
		if (uid == null) {
			System.out.println("参数为空");
			return false;
		}
		if (oneGid == null || "".equals(oneGid.trim()) || "2".equals(oneGid.trim())) {
			return this.baseEditGroupShip(uid);
		}
		String[] gids = null;
		if (isNoticeOfficer) {
			gids = new String[] { oneGid, "2" };// 2代表公告员，一个约定
		} else {
			gids = new String[] { oneGid };
		}
		return this.baseEditGroupShip(uid, gids);
	}

	// 事务注解
	@Transactional(rollbackFor = { Exception.class })
	private boolean baseEditGroupShip(String uid, String... gids) {
		// 判断用户,角色是否存在
		if (this.findById(uid) == null) {
			System.out.println(uid + ":用户不存在");
			return false;
		}
		if (gids != null) {
			for (String gid : gids) {
				if (gs.findById(gid) == null) {
					System.out.println(gid + ":角色不存在");
					return false;
				}
			}
		}
		// 删除旧关系
		List<Group> groups = this.findGroupsById(uid);
		if (groups != null) {
			for (Group group : groups) {
				is.deleteMembership(uid, group.getId());
			}
		}
		// 添加新关系
		if (gids != null) {
			for (String gid : gids) {
				is.createMembership(uid, gid);
			}
		}
		return true;
	}

	@Override
	public List<Group> findGroupsById(String uid) {
		if (uid != null) {
			return is.createGroupQuery().groupMember(uid).list();
		} else {
			return null;
		}

	}

	// 事务注解
	@Transactional(rollbackFor = { Exception.class })
	@Override
	public boolean addUserList(Set<User> users) {
		for (User user : users) {
			user.setPassword("12345");
			if (this.add(user)) {
				System.out.println(user.getId() + "号用户添加成功!");
			} else {
				return false;
			}
		}
		return true;
	}

	@Override
	public List<UserInfo> findUserInfosByUsers(List<User> users) {
		List<UserInfo> uis = null;
		if (users != null && users.size() > 0) {
			uis = new ArrayList<UserInfo>();
			UserInfo temp = null;
			for (User user : users) {
				temp = this.findUserInfoById(user.getId());
				if (temp != null) {
					uis.add(temp);
				}
			}
		}

		return uis;
	}

}
